package top.tenebrous.yzl.chat.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import top.tenebrous.yzl.basic.constant.Constants;
import top.tenebrous.yzl.basic.constant.ResultCode;
import top.tenebrous.yzl.basic.enums.DeleteStatus;
import top.tenebrous.yzl.basic.model.YzlChatResult;
import top.tenebrous.yzl.basic.utils.ReflectionUtils;
import top.tenebrous.yzl.chat.controller.BaseController;
import top.tenebrous.yzl.chat.domain.system.SysMenu;
import top.tenebrous.yzl.chat.service.system.ISysMenuService;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Api(tags = "菜单管理")
@RequestMapping("/sysMenu")
@RestController
@Slf4j
public class SysMenuController extends BaseController {

    @Resource
    private ISysMenuService sysMenuService;

//    @Resource
//    private ISysRoleMenuService sysRoleMenuService;
//
//    @Resource
//    private ISysRoleService sysRoleService;
//
//    @Resource
//    private ISysUserRoleService sysUserRoleService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostMapping(value = "/add")
    @ApiOperation(value = "新增菜单")
    public YzlChatResult add(@RequestBody SysMenu sysMenu) {
        //参数校验
        //1级菜单为顶级，没有上一级菜单,非顶级菜单上一级菜单不可空
        if (Constants.STRING_ONE.equals(sysMenu.getMenuLevel() + "")) {
            if (null != sysMenu.getParentId()) {
                //顶级菜单 没有上一级菜单
                return YzlChatResult.error(ResultCode.C500.getCode(), "新增菜单失败,顶级菜单没有上一级菜单");
            }
        } else {
            if (null == sysMenu.getParentId()) {
                //非顶级菜单上一级菜单不可空
                return YzlChatResult.error(ResultCode.C500.getCode(), "新增菜单失败,非顶级菜单上一级菜单不可空");
            }
        }
        sysMenu.setCreateUser(userInfo().getUserName());
        sysMenu.setUpdateUser(userInfo().getUserName());
        //菜单名校验
        ReflectionUtils.trim(sysMenu);
        sysMenu.setIsDeleted(DeleteStatus.DELETE_NO.getStatus());
        sysMenu.setCreateDate(new Date());
        sysMenu.setUpdateDate(new Date());
        sysMenu.setIsDeleted(DeleteStatus.DELETE_NO.getStatus());

        //1判断当前有没有父id 有父id说明是叶子节点  没有则说明是非叶子节点
        if (sysMenu.getParentId() != null && sysMenu.getParentId() > 0) {
            sysMenu.setIsLeaf(DeleteStatus.DELETE_YES.getStatus());
            //如果当前菜单是叶子节点 则判断父菜单是否为叶子节点 是则改为非叶子节点
            SysMenu one = sysMenuService.getOne(new LambdaQueryWrapper<SysMenu>().eq(null != sysMenu.getParentId(), SysMenu::getId, sysMenu.getParentId()));
            if (one != null && one.getIsLeaf() != null && one.getIsLeaf().equals(DeleteStatus.DELETE_YES.getStatus())) {
                one.setIsLeaf(DeleteStatus.DELETE_NO.getStatus());
                sysMenuService.updateById(one);
            }
        } else {
            sysMenu.setIsLeaf(DeleteStatus.DELETE_NO.getStatus());
        }
        boolean isOk = sysMenuService.save(sysMenu);
        if (isOk) {
            return YzlChatResult.success();
        }
        return YzlChatResult.error(ResultCode.C500.getCode(), "新增菜单失败");
    }

    private String getBearToken(String userToken) {
        return redisTemplate.opsForValue().get("app_token_" + userToken);
    }


    @PostMapping("/delete")
    @ApiOperation(value = "删除菜单")
    public YzlChatResult delete(@RequestBody Long ids[]) {
        boolean b = sysMenuService.removeByIds(Arrays.asList(ids));
        if (b) {
            return YzlChatResult.success();
        }
        return YzlChatResult.error(ResultCode.C500.getCode(), "删除菜单失败");
    }


    @PostMapping("/update")
    @ApiOperation(value = "修改菜单")
    @CacheEvict(cacheNames = "menuInfo_", key = "#sysMenu.getUpdateUser()")
    public YzlChatResult update(@RequestBody SysMenu sysMenu) {
        //参数校验
        //1级菜单为顶级，没有上一级菜单,非顶级菜单上一级菜单不可空
        if (Constants.STRING_ONE.equals(sysMenu.getMenuLevel() + "")) {
            if (null != sysMenu.getParentId()) {
                //顶级菜单 没有上一级菜单
                return YzlChatResult.error(ResultCode.C500.getCode(), "更新菜单失败,顶级菜单没有上一级菜单", null);
            }
        } else {
            if (null == sysMenu.getParentId()) {
                //非顶级菜单上一级菜单不可空
                return YzlChatResult.error(ResultCode.C500.getCode(), "更新菜单失败,非顶级菜单上一级菜单不可空", null);
            }
        }
        //判断父id和原来的父id是否一致 是则不更改叶子节点信息
        SysMenu sysMenuResult = sysMenuService.getById(sysMenu.getId());
        if (sysMenuResult != null && null != sysMenu.getParentId() && !sysMenu.getParentId().equals(sysMenuResult.getParentId())) {
            if (sysMenu.getParentId() != null) {
                // 否 2
                List<SysMenu> list = sysMenuService.list(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getParentId, sysMenuResult.getParentId()));
                //说明当前菜单的父菜单只有一个子菜单 需要改为叶子节点
                if (CollectionUtils.isNotEmpty(list) && list.size() < 2) {
                    sysMenuResult.setIsLeaf(1);
                    sysMenuService.updateById(sysMenuResult);
                }
                // 否1
                SysMenu parento = sysMenuService.getById(sysMenu.getId());
                if (null != parento && parento.getParentId() != null) {
                    parento.setIsLeaf(0);
                    sysMenuService.updateById(parento);
                }
            }
        }
        ReflectionUtils.trim(sysMenu);
        if (null != sysMenu.getId()) {
            sysMenu.setUpdateUser(userInfo().getUserName());
            sysMenu.setUpdateDate(new Date());
            boolean b = sysMenuService.updateById(sysMenu);
            if (b) {
                return YzlChatResult.success();
            }
        }
        return YzlChatResult.error(ResultCode.C500.getCode(), "修改菜单失败");
    }


    @GetMapping("/list")
    public YzlChatResult<Page<SysMenu>> list(@RequestParam(required = false) @ApiParam(name = "current", value = "当前页", required = false) Integer current,
                                         @RequestParam(required = false) @ApiParam(name = "size", value = "页条数", required = false) Integer size,
                                         @RequestParam(required = false) @ApiParam(name = "menuName", value = "菜单名称", required = false) String menuName,
                                         @RequestParam(required = false) @ApiParam(name = "bizType", value = "菜单所属", required = false) Integer bizType,
                                         @RequestParam(required = false) @ApiParam(name = "menuLevel", value = "菜单层级", required = false) Integer menuLevel,
                                         @RequestParam(required = false) @ApiParam(name = "parentName", value = "父菜单名称", required = false) String parentName,
                                         @RequestParam(required = false) @ApiParam(name = "menuLink", value = "菜单链接", required = false) String menuLink
    ) {
        try {
            SysMenu sysMenu = new SysMenu();
            sysMenu.setCurrent(current);
            sysMenu.setSize(size);
            sysMenu.setMenuName(menuName);
            sysMenu.setMenuLevel(menuLevel);
            sysMenu.setMenuLink(menuLink);
            sysMenu.setBizType(bizType);

            Page<SysMenu> page = new Page<>();
            page.addOrder(OrderItem.desc("id"));
            page.setCurrent(sysMenu.getCurrent());
            page.setSize(sysMenu.getSize());
            SysMenu parentMenu = new SysMenu();
            if (StringUtils.isNotEmpty(parentName)) {
                List<SysMenu> list = sysMenuService.list(new LambdaQueryWrapper<SysMenu>().eq(!StringUtils.isEmpty(parentName), SysMenu::getMenuName, parentName));
                if (CollectionUtils.isNotEmpty(list)) {
                    parentMenu = list.get(0);
                }

            }
            Page<SysMenu> pageInfo = sysMenuService.page(page, new LambdaQueryWrapper<SysMenu>()
                    .like(!StringUtils.isEmpty(sysMenu.getMenuName()), SysMenu::getMenuName, sysMenu.getMenuName())
                    .eq(null != sysMenu.getIsDeleted(), SysMenu::getIsDeleted, sysMenu.getIsDeleted())
                    .eq(null != sysMenu.getMenuLink(), SysMenu::getMenuLink, sysMenu.getMenuLink())
                    .eq(null != sysMenu.getBizType(), SysMenu::getBizType, sysMenu.getBizType())
                    .eq(null != sysMenu.getMenuLevel(), SysMenu::getMenuLevel, sysMenu.getMenuLevel())
                    .eq(null != parentMenu && null != parentMenu.getId(), SysMenu::getParentId, parentMenu.getId()));
            return YzlChatResult.success(pageInfo);
        } catch (Exception e) {
            log.error("查询菜单列表异常：{}", e);
            return YzlChatResult.error(500, "查询异常！");
        }

    }

//    @GetMapping("/menuBindList")
//    @ApiOperation(value = "获取不同业态各自对应菜单数据")
//    public YzlChatResult<MenuBindResDto> menuBindList(@RequestParam(required = false) @ApiParam(name = "bizType", value = "菜单所属", required = false) Integer bizType) {
//        MenuBindResDto menuBindResDto = new MenuBindResDto();
//        List<SysMenu> list = sysMenuService.list(new LambdaQueryWrapper<SysMenu>()
//                .eq(SysMenu::getIsDeleted, 0)
//                .eq(bizType != null, SysMenu::getBizType, bizType)
//                .orderByAsc(SysMenu::getBizType)
//        );
//        List<MenuResDto> menuList = BaseHelper.getMenuList(list);
//        menuBindResDto.setMenuList(menuList);
//        List<SysRoleMenu> sysRoleMenuList = sysRoleMenuService.list(new LambdaQueryWrapper<SysRoleMenu>()
//                .eq(SysRoleMenu::getIsDeleted, DeleteStatus.DELETE_NO.getStatus())
//        );
//        menuBindResDto.setSysRoleMenuList(sysRoleMenuList);
//        //查询末级菜单集合
//        return YzlChatResult.success(menuBindResDto);
//    }
//
//    private Set<Long> getMenuList() {
//        Set<Long> resSet = new HashSet<>();
//        List<SysUserRole> list = sysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, getUserId()));
//        if (CollectionUtils.isNotEmpty(list)) {
//            List<Long> collect = list.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
//            List<SysRoleMenu> menuList = sysRoleMenuService.list(new LambdaQueryWrapper<SysRoleMenu>().in(SysRoleMenu::getRoleId, collect));
//            if (CollectionUtils.isNotEmpty(menuList)) {
//                resSet = menuList.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toSet());
//            }
//        }
//        return resSet;
//    }


    @GetMapping("/query")
    @ApiOperation(value = "查询菜单详情")
    public YzlChatResult query(@RequestParam(required = true) @ApiParam(name = "id", value = "菜单id") Long id) {
        SysMenu one = sysMenuService.getOne(new LambdaQueryWrapper<SysMenu>().eq(null != id, SysMenu::getId, id));
        return YzlChatResult.success(one, "查询菜单成功");
    }


    @GetMapping("/querySelect")
    @ApiOperation(value = "查询菜单详情")
    public YzlChatResult queryList(@RequestParam(required = true) @ApiParam(name = "id", value = "菜单id") Long id) {
        SysMenu one = sysMenuService.getOne(new LambdaQueryWrapper<SysMenu>().eq(null != id, SysMenu::getId, id));
        return YzlChatResult.success(one, "查询菜单成功");
    }


}
